<template>
  <div class="cabinet_latte_contain">
    <div class="cabinet_latte_title">柜子设计器</div>

    <table
      border="1"
      id="cabinet_latte_table"
      align="center"
      width="100%"
      cellpadding="20"
      cellspacing="0"
      :key="renderTable"
    >
      <tr
        v-for="(row, index) in tableData"
        :key="index"
        :id="row.id"
      >
        <td
          @mousedown="handleMouseDown"
          @mouseup="handleMouseUp"
          v-for="(col, j) in row.col"
          :key="j"
          :id="col.id"
          :rowspan="col.rowspan"
          :colspan="col.colspan"
          :initRow="col.initRow"
          :initCol="col.initCol"
          :col="JSON.stringify(col)"
          v-show="!col.isMerge"
          @click="cellClick(col)"
          @contextmenu="openContextMenu($event)"
        >
          <div class="cell_info">
            <slot
              name="cellCard"
              :cell="col.cell"
              :tableData="tableData"
            ></slot>
          </div>
        </td>
      </tr>
    </table>
    <ContextMenuTool
      ref="contextMenuTool"
      @mergeCell="mergeCell"
      @splitCell="splitCell"
      @delRow="delRow"
      @delCol="delCol"
    ></ContextMenuTool>
  </div>
</template>
<script>
import guid from '@/utils/generator'
import ContextMenuTool from './ContextMenuTool.vue'

const STATUS = {
  CREATE: 0,
  UPDATE: 1,
  DETAIL: 2,
}
export default {
  components: {
    ContextMenuTool,
  },
  props: {
    setConfig: {
      type: Object,
      default: () => {
        return {
          row: 0,
          col: 0,
        }
      },
    },
    dialogStatus: {
      type: Number,
      default: 0,
    },
    cellData: {
      type: Array,
      default: () => [],
    },
    cellConfigList: {
      type: Array,
      default: () => [],
    },
    entity: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      dragging: false,
      clickCellID: '',
      startCell: null,
      columns: [], // 您的列配置
      chooseCellsArea: [],
      chooseCellIds: [],
      cellConfig: [],
      renderTable: 0,
      tableData: [],
      endCell: {},
    }
  },
  mounted() {
    this.setCellConfigList()
  },
  methods: {
    setCellConfigList() {
      console.log('this.cellConfigList', this.cellConfigList)
      if (this.cellConfigList.length > 0) {
        this.tableData = this.cellConfigList
        this.renderTable += 1
        this.setCellDataList()
      }
    },
    getCellConfigList() {
      const localTableData = JSON.parse(JSON.stringify(this.tableData))
      localTableData.forEach((row) => {
        row.col.forEach((col) => {
          delete col.cell // 删除cell对象
        })
      })
      return JSON.stringify(localTableData)
    },
    setCellDataList() {
      if (this.cellData.length > 0) {
        this.cellData.forEach((cell) => {
          // 遍历 tableData 数组
          this.tableData.forEach((row) => {
            // 在当前 row 的 col 数组中查找匹配的 cell
            const colItem = row.col.find((col) => col.id === cell.id)
            if (colItem) {
              // 替换 cell 对象
              colItem.cell = cell
            }
          })
        })

        this.renderTable += 1
      }
      console.log('this.tableData12313', this.tableData)
    },
    updateCellData(cell) {
      this.tableData.forEach((row) => {
        // 在当前 row 的 col 数组中查找匹配的 cell
        const colItem = row.col.find((col) => col.id === cell.id)
        if (colItem) {
          // 替换 cell 对象
          colItem.cell = {
            ...colItem.cell,
            ...cell,
          }
        }
      })
      this.renderTable += 1
    },
    getCellDataList() {
      const cells = this.tableData.reduce((acc, currentItem) => {
        // 对每个元素的 col 数组进行遍历，提取 cell 对象
        const cellsOfCurrentItem = currentItem.col.map((colItem) => colItem.cell)
        // 将当前项的 cells 添加到累积器数组中
        return acc.concat(cellsOfCurrentItem)
      }, []) // 初始累积器是一个空数组
      console.log('cells', cells)
      return cells
    },
    openContextMenu(event) {
      if (this.dialogStatus !== STATUS.CREATE) {
        // 不是新增就不可以打开右击菜单
        return
      }
      this.$nextTick(() => {
        event.preventDefault()
        const rowspan = parseInt(event.currentTarget.getAttribute('rowspan'), 10)
        const colspan = parseInt(event.currentTarget.getAttribute('colspan'), 10)
        let flag = false
        flag = (rowspan > 1 || colspan > 1) && this.chooseCellsArea.length === 1
        if (flag) {
          // 拆分
          this.cellClick(event.currentTarget)
        }
        if (this.chooseCellsArea.length < 2 && !flag) {
          this.cellClick(event.currentTarget)
        }
        this.$refs.contextMenuTool.openContextMenu(event, flag, this.chooseCellsArea.length < 2 && !flag)
      })
    },

    mergeCell() {
      // 计算起始单元格位置
      console.log('行，列', this.getCellRowCol(this.chooseCellsArea[0]))
      const chooseIds = this.chooseCellsArea.map((item) => {
        return item.id
      })
      //   console.log(' chooseIds', chooseIds);
      // 计算合并单元格的大小
      const mergeDimensions = this.calculateMergeDimensions(this.chooseCellsArea)
      console.log(`合并后的单元格将占据 ${mergeDimensions.numRows} 行 和 ${mergeDimensions.numCols} 列。`)
      this.mergeCellMethod(chooseIds, this.startCell.cellId, mergeDimensions.numRows, mergeDimensions.numCols)
      //   this.mergeCellMethod();

      this.chooseCellsArea = []
      console.log('this.tableData', this.tableData)
      this.renderTable += 1
    },
    splitCell() {
      // 拆分单元格
      //   console.log(this.chooseCellsArea[0]);
      const cellId = this.clickCellID

      let idsToUpdate = [cellId]
      this.tableData.forEach((row) => {
        row.col.forEach((col) => {
          if (col.id === cellId) {
            idsToUpdate = idsToUpdate.concat(col.mergeids)
          }
        })
      })

      // 更新tableData数组中的对象，如果它们的ID在idsToUpdate中
      this.tableData.forEach((row) => {
        row.col.forEach((col) => {
          if (idsToUpdate.includes(col.id)) {
            col.mergeids = []
            col.rowspan = 1
            col.colspan = 1
            col.isMerge = false
          }
        })
      })
      this.chooseCellsArea = []
      console.log('this.tableData', this.tableData)
      this.renderTable += 1
    },
    delRow() {
      const cellId = this.clickCellID
      // 查找包含该col id的对象的索引
      const parentIndex = this.tableData.findIndex((item) => item.col.some((col) => col.id === cellId))
      if (parentIndex !== -1) {
        this.tableData.splice(parentIndex, 1)
      }
      this.chooseCellsArea = []
      this.renderTable += 1
    },
    delCol() {
      const cellId = this.clickCellID
      let targetInitCol

      // 第一步：找到对应ID的对象并记录其initCol
      for (const item of this.tableData) {
        const found = item.col.find((col) => col.id === cellId)
        if (found) {
          targetInitCol = found.initCol
          break
        }
      }

      // 第二步：删除所有initCol等于targetInitCol的对象
      if (targetInitCol !== undefined) {
        for (const item of this.tableData) {
          item.col = item.col.filter((col) => col.initCol !== targetInitCol)
        }
      }
      this.chooseCellsArea = []
      this.renderTable += 1
    },
    // 合并单元格
    // mergeCellMethod() {
    //   const chooseIds = this.chooseCellsArea.map(item => {
    //     return item.id;
    //   });

    //   this.chooseCellsArea.forEach(cell => {
    //     const colObj = JSON.parse(cell.getAttribute('col'));
    //     if (colObj.mergeids.length > 0) {
    //       chooseIds.push(...colObj.mergeids);
    //     }
    //   });
    //   const idsToMergeExceptFirst = chooseIds.slice(1);
    //   this.tableData.forEach(item => {
    //     item.col.forEach(colItem => {
    //       if (idsToMergeExceptFirst.includes(colItem.id)) {
    //         colItem.isMerge = true;
    //       }
    //       if (chooseIds[0] === colItem.id) {
    //         colItem.mergeids = [...colItem.mergeids, ...idsToMergeExceptFirst];
    //       }
    //     });
    //   });
    // },
    // // 合并单元格
    mergeCellMethod(chooseIds, id, rowspan, colspan) {
      // 获取被合并的id
      const idsToMergeExceptFirst = chooseIds.slice(1)
      console.log('被合并的id', idsToMergeExceptFirst)
      let endRowspan = 1
      let endColspan = 1
      this.tableData.forEach((row) => {
        row.col.forEach((col, index) => {
          if (col.id === this.endCell.cellId) {
            endRowspan = col.rowspan
            endColspan = col.colspan
          }
        })
      })
      this.tableData.forEach((row) => {
        row.col.forEach((col, index) => {
          if (col.id === id) {
            col.rowspan = rowspan
            // col.colspan = col.colspan > 1 && colspan < col.colspan ? col.colspan : colspan;
            col.colspan = colspan
          }
        })
      })
      this.tableData.forEach((item) => {
        item.col.forEach((colItem) => {
          if (idsToMergeExceptFirst.includes(colItem.id)) {
            colItem.isMerge = true
          }
          if (chooseIds[0] === colItem.id) {
            colItem.mergeids = [...colItem.mergeids, ...idsToMergeExceptFirst]
          }
        })
      })
    },

    // 获取单元格位置信息
    getCellRowCol(cell) {
      const row = cell.parentNode.rowIndex
      const column = cell.cellIndex
      return {
        row,
        col: column,
      }
    },
    // 计算合并单元格的大小
    calculateMergeDimensions(chooseCellsArea) {
      let minRowIndex = Infinity
      let maxRowIndex = -Infinity
      let minCellIndex = Infinity
      let maxCellIndex = -Infinity

      chooseCellsArea.forEach((cell) => {
        const rowIndex = parseInt(cell.getAttribute('initrow'), 10)
        const cellIndex = parseInt(cell.getAttribute('initcol'), 10)
        // const { rowIndex } = cell.parentNode; // 获取当前单元格的行索引
        // const { cellIndex } = cell; // 获取当前单元格的列索引

        // 更新行索引的最小和最大值
        minRowIndex = Math.min(minRowIndex, rowIndex)
        maxRowIndex = Math.max(maxRowIndex, rowIndex)

        // 更新列索引的最小和最大值
        minCellIndex = Math.min(minCellIndex, cellIndex)
        maxCellIndex = Math.max(maxCellIndex, cellIndex)
      })

      // 计算合并后单元格应占据的行数和列数
      const numRows = maxRowIndex - minRowIndex + 1
      const numCols = maxCellIndex - minCellIndex + 1

      return { numRows, numCols }
    },
    handleMouseDown(event) {
      this.$nextTick(() => {
        if (event.button === 0) {
          this.dragging = true

          // 获取起始单元格信息，这里可能需要一些逻辑来确定单元格的行和列
          const target = event.currentTarget
          console.log('摁下target', target)
          if (target) {
            const row = Number(target.attributes.initrow.value)
            const col = Number(target.attributes.initcol.value)
            const cellId = target.id
            this.startCell = { cellId, row, col }

            //   console.log('初始单元格', this.startCell);
          }

          // 添加全局鼠标移动事件监听
          window.addEventListener('mousemove', this.handleMouseMove)
        }
      })
    },
    handleMouseUp(event) {
      this.dragging = false

      // 移除全局鼠标移动事件监听
      window.removeEventListener('mousemove', this.handleMouseMove)
    },

    handleMouseMove(event) {
      //   if (!this.dragging) {
      //     return;
      //   }
      //   console.log('的高亮显示');
      // 这里可以根据需要添加逻辑，例如更新当前单元格的高亮显示
      this.$nextTick(() => {})
      if (event.button === 0) {
        const { target } = event
        // console.log('target.parentNode', event);
        if (target) {
          const row = Number(target.attributes.initrow.value)
          const col = Number(target.attributes.initcol.value)

          // 根据 startCell 和当前单元格计算覆盖的单元格
          console.log(`Selected cells from (${this.startCell.row}, ${this.startCell.col}) to (${row}, ${col})`)
          // const cell = this.getTableCellByIdx('cabinet_latte_table', row, column);
          this.endCell = {
            cellId: target.id,
            row,
            col,
          }

          //   this.applyBorderStyles('cabinet_latte_table', this.startCell.row, this.startCell.col, row, col, target.id);
          this.getChooseCellRange('cabinet_latte_table', this.startCell.row, this.startCell.col, row, col, target.id)
        }
      }
    },
    // eslint-disable-next-line consistent-return
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      //  :span-method="objectSpanMethod"
      if (this.cellConfig.length > 0) {
        if (columnIndex === 2) {
          if (rowIndex === 2) {
            return [5, 2]
          }
        }
      }
    },
    cellClick(col) {
      this.clickCellID = col.id
      const cell = document.getElementById(col.id)
      console.log(cell)
      this.chooseCellsArea = [cell]
      this.clearBorderStyles('cabinet_latte_table')
      cell.style.border = '4px solid #409eff'
    },

    clearBorderStyles(tableId) {
      const rowList = document.getElementById(tableId).querySelectorAll('tr')
      if (!rowList) return

      // 遍历所有行和单元格，清除边框样式
      for (const row of rowList) {
        for (const cell of row.cells) {
          cell.style.borderTop = ''
          cell.style.borderBottom = ''
          cell.style.borderLeft = ''
          cell.style.borderRight = ''
          cell.style.backgroundColor = 'transparent'
        }
      }
    },
    getChooseCellRange(tableId, startRow, startCol, endRow, endCol, endId) {
      this.clearBorderStyles(tableId)
      const cellList = document.getElementById(tableId).querySelectorAll('td')
      const endRowNum = endRow
      const endColNum = endCol
      const cellsInRange = []
      const cellsIdsRange = []
      cellList.forEach((cell) => {
        const initRow = parseInt(cell.getAttribute('initrow'), 10)
        const initCol = parseInt(cell.getAttribute('initcol'), 10)

        // if (cell.id === endId && (cell.rowSpan !== 1 || cell.rowCol !== 1)) {
        //   endRowNum = cell.rowSpan === 1 ? endRow : cell.rowSpan;
        //   endColNum = cell.colSpan === 1 ? endCol : cell.colSpan;
        // }
        // 判断单元格是否在指定范围内
        if (initRow >= startRow && initRow <= endRowNum && initCol >= startCol && initCol <= endColNum) {
          cellsInRange.push(cell)
          const endCell = this.getComputedStyleRanges(cellsInRange, tableId, startRow, startCol, endRow, endCol)
          //   this.chooseCellsArea = cellsInRange;
          //   cell.style.backgroundColor = '#c0bfbf';
          this.applyBorderStyles(tableId, startRow, startCol, endCell.endRow, endCell.endCol)
        }
      })
    },
    // 获取范围并且将改变边框颜色
    applyBorderStyles(tableId, startRow, startCol, endRow, endCol) {
      this.clearBorderStyles(tableId)
      const cellList = document.getElementById(tableId).querySelectorAll('td')
      //   let endRowNum = endRow;
      //   let endColNum = endCol;
      const cellsInRange = []
      const cellsIdsRange = []
      cellList.forEach((cell) => {
        const initRow = parseInt(cell.getAttribute('initrow'), 10)
        const initCol = parseInt(cell.getAttribute('initcol'), 10)
        // 判断单元格是否在指定范围内
        if (initRow >= startRow && initRow <= endRow && initCol >= startCol && initCol <= endCol) {
          cellsInRange.push(cell)

          this.chooseCellsArea = cellsInRange

          cell.style.backgroundColor = '#c0bfbf'
          // 应用顶部边框样式
          if (initRow === startRow) {
            cell.style.borderTop = '4px solid #409eff'
          }

          // 应用底部边框样式
          if (initRow === endRow) {
            cell.style.borderBottom = '4px solid #409eff'
          }

          // 应用左侧边框样式
          if (initCol === startCol) {
            cell.style.borderLeft = '4px solid #409eff'
          }

          // 应用右侧边框样式
          if (initCol === endCol) {
            cell.style.borderRight = '4px solid #409eff'
          }
        }
      })
      console.log('选中的单元格', this.chooseCellsArea)
    },
    findElementByInitPosition(row, col) {
      // 遍历tableData数组
      for (const rowData of this.tableData) {
        // 使用filter方法查找col数组中符合条件的元素
        const matchedElements = rowData.col.filter((element) => element.initRow === row && element.initCol === col)

        // 如果找到匹配的元素，返回第一个匹配的元素
        if (matchedElements.length > 0) {
          return matchedElements[0] // 返回找到的第一个匹配元素
        }
      }
      // 如果没有找到匹配的元素，返回null
      return null
    },
    // 获取包含选中单元格的最大范围
    getComputedStyleRanges(cells, tableId, startRow, startCol, endRow, endCol) {
      let maxCol = 0
      let maxRow = 0
      cells.forEach((cell) => {
        const colObj = JSON.parse(cell.getAttribute('col'))

        const colnum = colObj.initCol + (colObj.colspan - 1)
        const rownum = colObj.initRow + (colObj.rowspan - 1)
        if (colnum > maxCol) {
          maxCol = colnum
        }
        if (rownum > maxRow) {
          maxRow = rownum
        }
      })

      return {
        endCol: maxCol,
        endRow: maxRow,
      }
    },
    generate2DArray(setConfig) {
      // 创建一个空数组用于存储结果
      const result = []

      // 遍历行数
      for (let i = 0; i < setConfig.row; i += 1) {
        // 为每一行创建一个对象，使用guid()函数生成id
        const rowObject = {
          id: guid(), // 假设guid()是你提到的用于生成唯一id的函数
          col: [],
        }

        // 遍历列数
        for (let j = 0; j < setConfig.col; j += 1) {
          // 为每一列创建一个对象，同样使用guid()函数生成id
          const cellId = guid()
          rowObject.col.push({
            id: cellId,
            rowspan: 1,
            colspan: 1,
            initRow: i,
            initCol: j,
            isMerge: false,
            mergeids: [],
            cell: {
              id: cellId,
              no: this.entity.containerName ? `${this.entity.containerName} ${i + 1} - ${j + 1}` : `${i + 1} - ${j + 1}`,
              storageLimit: this.entity.defaultStorageLimit,
              rowIndex: i + 1,
              columnIndex: j + 1,
            },
          })
        }

        // 将这一行的对象添加到结果数组中
        result.push(rowObject)
      }

      // 返回生成的二维数组
      return result
    },
    // 设置柜子名称
    setContainerName(containerName) {
      this.tableData.forEach((row) => {
        row.col.forEach((col) => {
          col.cell.no = `${containerName + col.cell.rowIndex}-${col.cell.columnIndex}` // 为每个cell对象添加containerName属性
        })
      })

      this.renderTable += 1
    },
    SetCellProperty(propName, propValue) {
      this.tableData.forEach((row) => {
        row.col.forEach((col) => {
          col.cell[propName] = propValue // 为每个cell对象添加containerName属性
        })
      })

      this.renderTable += 1
    },
  },
  watch: {
    setConfig: {
      handler(val) {
        if (this.cellConfigList.length < 1) {
          if (val.row && val.col) {
            if (this.tableData.length > val.row) {
              this.tableData = this.tableData.splice(0, val.row)
            } else {
              this.tableData = this.generate2DArray(val)
            }
          }
        }
        console.log(' this.tableDatathis.cellConfigList', this.cellConfigList)
      },
      deep: true,
      immediate: true,
    },
    'entity.containerName': {
      handler(val) {
        if (this.tableData.length > 0 && this.cellConfigList.length < 1) {
          this.setContainerName(val)
        }
      },
      deep: true,
    },
    'entity.defaultStorageLimit': {
      handler(val) {
        if (this.tableData.length > 0 && this.cellConfigList.length < 1) {
          this.SetCellProperty('storageLimit', val)
        }
      },
      deep: true,
    },
  },
}
</script>
<style lang="scss" scoped>
.cabinet_latte_contain {
  .cabinet_latte_title {
    width: 100%;
    padding: 0 20px;
    font-family: KaiTi, Microsoft YaHei;
    font-size: 20px;
    color: #606266;
    line-height: 32px;
    font-weight: 600;
  }
  #cabinet_latte_table {
    margin-top: 20px;
    user-select: none;
    td {
      //   padding: 0;
      .cell_info {
        width: 100%;
        height: 100%;
      }
      .cell_btn {
        width: fit-content;
      }
    }
    ::v-deep .el-descriptions__body {
      background-color: transparent;
    }
  }
  ::v-deep .el-table thead {
    display: none;
    ::v-deep .el-table__row {
      border: 1px solid black;
      border-bottom: 0px;
    }
  }

  ::v-deep .el-table .el-table__body td,
  .el-table .el-table__header,
  .el-table .el-table__body tr,
  .el-table .el-table__header-wrapper {
    border: 1px solid black;
  }

  .el-table__body-wrapper {
    border: 1px solid rgb(0, 0, 0);
    border-bottom: 0px;
  }
  ::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
    background-color: transparent;
  }
}
</style>
